package com.eden.api.controller;

import com.eden.api.controller.vo.ApiResult;
import com.eden.api.security.JwtUser;
import com.eden.api.security.LoginUser;
import com.eden.api.security.annotation.AnonymousAccess;
import com.eden.api.utils.PropertyReader;
import com.eden.common.core.page.PageDomain;
import com.eden.common.core.page.TableDataInfo;
import com.eden.common.core.page.TableSupport;
import com.eden.common.utils.DateUtils;
import com.eden.common.utils.ServletUtils;
import com.eden.common.utils.StringUtils;
import com.eden.common.utils.sql.SqlUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * @program: eden
 * @description: ${description}
 * @author: Mr.Jiao
 * @create: 2020-09-14 17:37
 */

public class ApiBaseController {

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 设置请求排序数据
     */
    protected void startOrderBy() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.orderBy(orderBy);
        }
    }

    /**
     * 获取request
     */
    public HttpServletRequest getRequest() {
        return ServletUtils.getRequest();
    }

    /**
     * 获取response
     */
    public HttpServletResponse getResponse() {
        return ServletUtils.getResponse();
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected ApiResult toAjax(int rows) {
        return rows > 0 ? success() : error();
    }

    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    protected ApiResult toAjax(boolean result) {
        return result ? success() : error();
    }

    /**
     * 返回成功
     */
    public ApiResult success() {
        return ApiResult.success();
    }

    /**
     * 返回失败消息
     */
    public ApiResult error() {
        return ApiResult.error();
    }

    /**
     * 返回成功消息
     */
    public ApiResult success(String message) {
        return ApiResult.success(message);
    }

    /**
     * 返回成功消息
     */
    public ApiResult success(Object data) {
        return ApiResult.success(data);
    }

    /**
     * 返回成功消息
     */
    public ApiResult success(String message, Object data) {
        return ApiResult.success(message, data);
    }

    /**
     * 返回失败消息
     */
    public ApiResult error(String message) {
        return ApiResult.error(message);
    }

    /**
     * 返回错误码消息
     */
    public ApiResult error(int code, String message) {
        return ApiResult.error(code, message);
    }

    public ApiResult error(String message, Object data) {
        return ApiResult.error(message, data);
    }

    /**
     * 返回错误码消息
     */
    public ApiResult error(int code, String message, Object data) {
        return ApiResult.error(code, message, data);
    }

    /**
     * 页面跳转
     */
    public String redirect(String url)
    {
        return StringUtils.format("redirect:{}", url);
    }

    /**
     * 获取消息头
     */
    protected String getHeader(String headerName) {
        return getRequest().getHeader(headerName);
    }

    /**
     * 设置消息头
     */
    protected void setHeader(String headerName, String headerValue) {
        getResponse().setHeader(headerName, headerValue);
    }

    /**
     * @description: 仅限于经AuthenticationInterceptor拦截过的controller使用。
     *               即方法被@AnonymousAccess {@link AnonymousAccess}修饰则不能调用
     * @date: 2019/11/4 17:59
     * @author: wenqing
     * @param
     * @return: com.nantian.api.security.LoginUser {@link com.eden.api.security.LoginUser}
     * @throws:
     */
    protected final LoginUser getLoginUser() {
        return JwtUser.getInstance().getLoginUser();
    }

    /**
     * @description: 仅限于经AuthenticationInterceptor拦截过的controller使用。
     *               即方法被@AnonymousAccess {@link AnonymousAccess}修饰则不能调用
     * @date: 2019/11/4 17:58
     * @author: wenqing
     * @param
     * @return: java.lang.Long
     * @throws:
     */
    protected final Long getUserId() {
        return JwtUser.getInstance().getUserId();
    }

    /**
     * @description: 仅限于经AuthenticationInterceptor拦截过的controller使用。
     *               即方法被@AnonymousAccess {@link AnonymousAccess}修饰则不能调用
     * @date: 2019/11/4 17:58
     * @author: wenqing
     * @param
     * @return: java.lang.String
     * @throws:
     */
    protected final String getLoginName() {
        return JwtUser.getInstance().getLoginName();
    }

    public static URL getURL(String resourceLocation)
            throws FileNotFoundException {
        if (resourceLocation.startsWith("classpath:")) {
            String path = resourceLocation.substring("classpath:".length());
            URL url = getDefaultClassLoader().getResource(path);
            if (url == null) {
                String description = "class path resource [" + path + "]";
                throw new FileNotFoundException(
                        description
                                + " cannot be resolved to URL because it does not exist");
            }
            return url;
        }
        try {
            return new URL(resourceLocation);
        } catch (MalformedURLException ex) {
            try {
                return new File(resourceLocation).toURI().toURL();
            } catch (MalformedURLException ex2) {
                throw new FileNotFoundException("Resource location ["
                        + resourceLocation
                        + "] is neither a URL not a well-formed file path");
            }
        }
    }

    public static ClassLoader getDefaultClassLoader() {
        ClassLoader cl = null;
        try {
            cl = Thread.currentThread().getContextClassLoader();
        } catch (Throwable ex) {
        }
        if (cl == null) {
            cl = PropertyReader.class.getClassLoader();
        }
        return cl;
    }
}
